package com.heimo.agentlicence.ui.fragment;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.heimo.agentlicence.R;
import com.heimo.agentlicence.model.AgentRecord;
import com.heimo.agentlicence.task.LicenceCheckTask;
import com.heimo.agentlicence.task.LicenceLoadTask;
import com.heimo.agentlicence.task.OnTaskCompleted;
import com.heimo.agentlicence.ui.DialogHelper;
import com.heimo.agentlicence.ui.adaptor.ListItemAdaptor;
import com.heimo.agentlicence.ui.adaptor.ScreenSlidePagerAdapter;

public class CheckLicenceFragment extends BasicFragment {
	private final String TAG = "CheckLicenceFragment";
	private EditText licenceView, licenceViewPre;
	private ListView listRecord;
	private List<NameValuePair> nvps;

	public static CheckLicenceFragment newInstance(Context ctx,
			ScreenSlidePagerAdapter adp) {
		CheckLicenceFragment f = new CheckLicenceFragment();
		f.setContext(ctx);
		f.setAdapter(adp);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = (ViewGroup) inflater.inflate(R.layout.activity_check_licence,
				container, false);
		init();
		return v;
	}

	private void init() {
		listRecord = (ListView) v.findViewById(R.id.listrecord);
		licenceView = (EditText) v.findViewById(R.id.licenceno);
		licenceViewPre = (EditText) v.findViewById(R.id.licenceno_pre);

		TextView tx = (TextView) v.findViewById(R.id.title);
		TextView txSep = (TextView) v.findViewById(R.id.labelSeperator);

		Typeface tf = Typeface.createFromAsset(ctx.getAssets(),
				"fonts/orbitron-bold.otf");
		tx.setTypeface(tf);
		txSep.setTypeface(tf);
		fnAllowSwipe(false);
		initBtnEvent();
	}

	private void initBtnEvent() {
		Button btnCheck = (Button) v.findViewById(R.id.btnSubmit);
		OnClickListener onClick = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Log.d(TAG, "fnCheck()");
				fnSetLicence(null);
				fnCloseSoftKeyboard();
				fnAllowSwipe(false);
				fnLoadPage();
			}
		};
		btnCheck.setOnClickListener(onClick);
	}

	private void fnCloseSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) ctx
				.getSystemService(ctx.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(licenceView.getWindowToken(), 0);
	}

	private void fnAllowSwipe(boolean allowSwipe) {
		fnShowIndicator(allowSwipe);
	}

	private void fnShowIndicator(boolean show) {
		ImageView imgRight = (ImageView) v.findViewById(R.id.overlayRight);
		if (show) {
			imgRight.setVisibility(View.VISIBLE);
		} else {
			imgRight.setVisibility(View.INVISIBLE);
		}
	}

	private void fnSetLicenceNo() {
		String licenceNo = licenceView.getText().toString();
		String licenceNoPre = licenceViewPre.getText().toString();
		licenceNo = (licenceNoPre + "-" + licenceNo);
		String tempName = "";
		if (nvps != null) {
			for (int i = 0; i < nvps.size(); i++) {
				NameValuePair nvp = nvps.get(i);
				if (nvp.getName().contains("LicenceNo")) {
					tempName = nvp.getName();
					nvps.remove(i);
				}
				if (nvp.getName().equalsIgnoreCase("ScrollTop")) {
					nvps.remove(i);
				}
			}
			nvps.add(new BasicNameValuePair(tempName, licenceNo));
		}
	}

	private void fnLoadPage() {
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object s) {
				nvps = (List<NameValuePair>) s;
				fnSetLicenceNo();
				fnSendCheckRequest();
			}

			public void onTaskFailed(String errMessage) {
				Log.d(TAG, errMessage);
				DialogHelper.getOkAlertDialog(ctx, "Error Fail", errMessage)
						.show();
			}
		};
		LicenceLoadTask llt = new LicenceLoadTask(ctx, completeAction);
		llt.fnLoadPage();
	}
	
	private void fnSetLicence(String r) {
		adapter.updateLicence(r);
	}
	
	private void fnSendCheckRequest() {
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object s) {
				List<AgentRecord> records = (List<AgentRecord>) s;
				if (records.size() <= 0) {
					fnClearList();
					DialogHelper
							.getOkAlertDialog(ctx,
									"No records has been found.",
									"Please check again.").show();
				} else {
					ListItemAdaptor adp = new ListItemAdaptor(ctx, records);
					listRecord.setAdapter(adp);
					fnSetLicence(records.get(0).getLicence());
					fnAllowSwipe(true);
//					Toast.makeText(ctx, "Data loaded successfully.",
//							Toast.LENGTH_LONG).show();
				}
			}

			public void onTaskFailed(String errMessage) {
				Log.d(TAG, errMessage);
				DialogHelper.getOkAlertDialog(ctx, "Error Fail", errMessage)
						.show();
			}
		};
		LicenceCheckTask llt = new LicenceCheckTask(ctx, completeAction);
		llt.fnLoadPage(nvps);
	}
	
	private void fnClearList() {
		ListAdapter adp = listRecord.getAdapter();
		if(adp!=null){
			((ListItemAdaptor)adp).removeAll();
		}
	}
}
